import 'package:acgn_pioneer/components/book-item/book1.dart';
import 'package:acgn_pioneer/models/sort_comic_model.dart';
import 'package:acgn_pioneer/pages/reader/reader_page_main.dart';
import 'package:acgn_pioneer/pages/sort/select_comp.dart';
import 'package:acgn_pioneer/utils/pop_util.dart';
import 'package:flutter/widgets.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../public.dart';

/// 分类-分类tab
class SortCatalogPage extends StatefulWidget {
  SortCatalogPage({Key key}) : super(key: key);

  @override
  SortCatalogPageState createState() => SortCatalogPageState();
}

class SortCatalogPageState extends State<SortCatalogPage>
    with AutomaticKeepAliveClientMixin {
  List<SimpleKeyModel> lstType = List<SimpleKeyModel>();
  List<SimpleKeyModel> lstStatus = [
    SimpleKeyModel(label: '全部', value: '0', key: 'status_id'),
    SimpleKeyModel(label: '连载', value: '1', key: 'status_id'),
    SimpleKeyModel(label: '完结', value: '2', key: 'status_id')
  ];
  List<SimpleKeyModel> lstMan = [
    SimpleKeyModel(label: '全部', value: '0', key: 'human_type'),
    SimpleKeyModel(label: '男生', value: '1', key: 'human_type'),
    SimpleKeyModel(label: '女生', value: '2', key: 'human_type')
  ];
  List<SimpleKeyModel> lstOrder = [
    SimpleKeyModel(label: '最近更新', value: 'date', key: 'orderModel'),
    SimpleKeyModel(label: '追更最多', value: 'shoucang', key: 'orderModel')
  ];
  SimpleKeyModel typeModel; // 类型
  SimpleKeyModel statusModel; // 状态
  SimpleKeyModel manModel; // 性别
  SimpleKeyModel orderModel; // 排序
  List<SortComicModel> lstComic = List<SortComicModel>(); // 漫画
  int page = 1;

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    statusModel = lstStatus[0];
    manModel = lstMan[0];
    orderModel = lstOrder[0];
    getList();
    initSortConfig();
  }

  @override
  void dispose() {
    super.dispose();
  }

  getList({bool refresh = true, bool clear: true}) async {
    if (clear) {
      page = 1;
      lstComic.clear();
    } else {
      page += 1;
    }
    var re = await SortService.getSortlist(
        orderby: orderModel.value,
        man: manModel.value,
        status: statusModel.value,
        type: typeModel?.key,
        page: page,
        pagesize: 30);
    if (re.length < 30) {
      _refreshController.loadNoData();
    } else {
      _refreshController.resetNoData();
    }
    lstComic.addAll(re);

    if (refresh) {
      setState(() {});
    }
  }

  initSortConfig() async {
    lstType = await SortService.getSortConfig();
    lstType.insert(0, SimpleKeyModel(label: '全部', value: '', key: ''));
    typeModel = lstType[0]; // 类型

    setState(() {});
  }

  void _onRefresh() async {
    await this.getList(refresh: false);
    if (mounted) setState(() {});
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    await this.getList(clear: false, refresh: false);
    if (mounted) setState(() {});
    _refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      width: ScreenUtil.getInstance().screenWidth,
      child: Padding(
          padding: EdgeInsets.all(16),
          child: RefreshConfig(
              child: SmartRefresher(
                  enablePullDown: true,
                  enablePullUp: true,
                  controller: _refreshController,
                  onRefresh: _onRefresh,
                  onLoading: _onLoading,
                  child: CustomScrollView(slivers: <Widget>[
                    buildSelectTypeView(),
                    buildStatusTypeView(),
                    buildManTypeView(),
                    buildTimeView(),
                    lstComic.length > 0
                        ? buildContentView()
                        : SliverToBoxAdapter(),
                  ])))),
    );
  }

  buildSelectTypeView() {
    return SelectComp(
      onTap: (SimpleKeyModel model) {
        typeModel = model;
        getList();
      },
      lst: lstType,
    );
  }

  buildStatusTypeView() {
    return SelectComp(
      onTap: (SimpleKeyModel model) {
        statusModel = model;
        getList();
      },
      lst: lstStatus,
    );
  }

  buildManTypeView() {
    return SelectComp(
      onTap: (SimpleKeyModel model) {
        manModel = model;
        getList();
      },
      lst: lstMan,
    );
  }

  buildTimeView() {
    TextStyle selectStyle =
        TextStyle(fontSize: 16, color: ColorUtil.rgba(255, 255, 255, 1));
    TextStyle normalStyle =
        TextStyle(fontSize: 16, color: ColorUtil.rgba(255, 255, 255, 0.6));
    return SliverPadding(
      padding: EdgeInsets.only(bottom: 16, top: 10),
      sliver: SliverToBoxAdapter(
          child: Row(children: [
        GestureDetector(
            onTap: () {
              orderModel = lstOrder[0];
              getList();
            },
            child: Text('最近更新',
                style: isSelect(lstOrder[0]) ? selectStyle : normalStyle)),
        SizedBox(width: 10),
        GestureDetector(
            onTap: () {
              orderModel = lstOrder[1];
              getList();
            },
            child: Text('追更更多',
                style: isSelect(lstOrder[1]) ? selectStyle : normalStyle))
      ])),
    );
  }

  isSelect(SimpleKeyModel model) {
    return orderModel.value == model.value;
  }

  showPopComic(int comicId, List<dynamic> comicIds) {
    PopUtil.showSlidePop(
        context: context,
        child: ReaderPageMain(
            comicIds: comicIds, comicId: comicId, isPopNested: true));
  }

  /// 漫画
  buildContentView() {
    return SliverGrid(
        delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
          var model = lstComic[index];
          return GestureDetector(
              onTap: () {
                showPopComic(
                    model.comicId, lstComic.map((e) => e.comicId).toList());
              },
              child: Book1Component(
                  cover: model.coverImg,
                  title: model.comicName,
                  desc: StringUtil.getTimeSpan(model.updateTime, 'yyyy.MM.dd') +
                      '更新'));
        }, childCount: lstComic.length),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            childAspectRatio: 105 / 190,
            crossAxisSpacing: Rem(14),
            mainAxisSpacing: Rem(14)));
  }
}
